﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.Globalization;

namespace Prerequisites.Binders
{
    public class GridModelModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.PropertyType == typeof(DateTime))
            {
                try
                {
                    var model = bindingContext.Model;
                    PropertyInfo property = model.GetType().GetProperty(propertyDescriptor.Name);

                    var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);

                    if (value != null)
                    {
                        var date = DateTime.ParseExact(value.AttemptedValue, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                        property.SetValue(model, date, null);
                    }
                }
                catch
                {
                    //If something wrong, validation should take care
                }
            }
            else
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }

    }
}